package com.gxxy.spring.kp03_aop.cls01_proxy.s2_dynamic.k01_interface;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

// 通过实现接口java.lang.reflect.InvocationHandler的方式实现动态的代理 

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class DynamicProxyTest {

	@Autowired
	private IStudentService service;
	
	@Autowired
	private TransactionManager txMgr;

	@Test
	public void testDynamicProxy() throws Exception {

		Class<?> cls = IStudentService.class;
		//Class<?> cls = service.getClass();
		
		//ClassLoader loader: 
		ClassLoader loader = cls.getClassLoader();

		//Class<?>[] interfaces:
		Class<?>[] interfaces = new Class<?>[] { cls };

		//InvocationHandler h:
		InvocationHandler handler = new TransactionInvocationHandler(service, txMgr);
		
		IStudentService proxy = (IStudentService) Proxy.newProxyInstance(
				loader, interfaces, handler);
		proxy.save(new Student("Rose", 18));
		
	}

}
